from django.forms import model_to_dict
from rest_framework import serializers


from apps.publish.models import PublishModel


# 模板 序列化器
class IndexSerializers(serializers.ModelSerializer):
    # model_to_dict 方法将字符串转换成字典
    # 由于直接使用默认值，页面会显示的是对象，不是一个具体的值，所以要自定义默认值
    user = serializers.SerializerMethodField()
    topic = serializers.SerializerMethodField()
    createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M")

    class Meta:
        model = PublishModel
        fields = ["id","cover","text","topic","user","favor_count","createTime"]

    def get_user(self,obj):
        return model_to_dict(obj.user,fields=['id','nickName','avatarUrl'])

    def get_topic(self,obj):
        return model_to_dict(obj.topic,fields=['id','topic','count'])